package com.bx.implatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bx.imcommon.enums.IMUserOnlineStatus;
import com.bx.implatform.dto.BoxMessageDTO;
import com.bx.implatform.dto.SearchBoxMessageDTO;
import com.bx.implatform.entity.Friend;
import com.bx.implatform.entity.User;
import com.bx.implatform.entity.UserBoxMessage;
import com.bx.implatform.mapper.UserBoxMessageMapper;
import com.bx.implatform.service.*;
import com.bx.implatform.session.SessionContext;
import com.bx.implatform.session.UserSession;
import com.bx.implatform.util.BeanUtils;
import com.bx.implatform.vo.UserBlackVO;
import com.bx.implatform.vo.UserBoxMessageVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserBoxMessageServiceImpl extends ServiceImpl<UserBoxMessageMapper, UserBoxMessage>
    implements UserBoxMessageService {

    private final UserBoxMessageMapper boxMessageMapper;

    private final UserService userService;

    private final FriendService friendService;

    private final UserBlacklistService blacklistService;


    @Override
    public boolean send(BoxMessageDTO dto) {
        UserSession session = SessionContext.getSession();
        UserBoxMessage message = new UserBoxMessage();
        message.setSendId(session.getUserId());
        message.setContent(dto.getContent());
        log.info("发送盲盒消息，用户id:{},盲盒内容:{}", session.getUserId(), dto.getContent());
        return boxMessageMapper.insert(message) >0;

    }

    @Override
    public UserBoxMessageVO receive(SearchBoxMessageDTO dto) {
        UserSession session = SessionContext.getSession();
        List<Long> filterUserIds = new ArrayList<>();
        filterUserIds.add(session.getUserId());
        //查询当前用户好友信息
        List<Friend> friends = friendService.findFriendByUserId(session.getUserId());
        //查询当前用户黑名单列表
        List<UserBlackVO> blackList = blacklistService.selectUserBlacklist(session.getUserId());
        if (!friends.isEmpty()){
            List<Long> friendIds = friends.stream().map(Friend::getFriendId).collect(Collectors.toList());
            filterUserIds.addAll(friendIds);
        }
        if (!blackList.isEmpty()){
            List<Long> blackIds = blackList.stream().map(UserBlackVO::getId).collect(Collectors.toList());
            filterUserIds.addAll(blackIds);
        }
        //查询不在黑名单和好友列表中的用户信息(按最近登录时间取最新50个用户)
        List<User> listUsers = userService.selectNonFriendUsers(filterUserIds, dto.getSex());

        //获取用户ID
        Long userId = getUserId(listUsers);
        //查询用户盲盒消息
        List<UserBoxMessage> listMessage = boxMessageMapper.selectList(Wrappers.<UserBoxMessage>lambdaQuery().eq(UserBoxMessage::getSendId, userId)
                .orderByDesc(UserBoxMessage::getCreateTime)
                .last(" limit 10"));
        if (listMessage.isEmpty()) {
            return null;
        }
        //随机选择一条盲盒消息
        Random random = new Random();
        int index = random.nextInt(listMessage.size());
        UserBoxMessage message = listMessage.get(index);

        UserBoxMessageVO messageVO = BeanUtils.copyProperties(message, UserBoxMessageVO.class);
        User user = userService.getById(message.getSendId());
        messageVO.setHeadImageThumb(user.getHeadImageThumb());
        messageVO.setNickName(user.getNickName());
        messageVO.setSex(user.getSex());
        return messageVO;
    }

    @Override
    public List<UserBoxMessage> findHistoryBoxMessage(Long page, Long size) {
        page = page > 0 ? page : 1;
        size = size > 0 ? size : 10;
        Long userId = SessionContext.getSession().getUserId();
        long stIdx = (page - 1) * size;
        QueryWrapper<UserBoxMessage> wrapper = new QueryWrapper<>();
        wrapper.lambda().and(wp -> wp.eq(UserBoxMessage::getSendId, userId)).orderByDesc(UserBoxMessage::getCreateTime)
                .last("limit " + stIdx + "," + size);

        List<UserBoxMessage> messages = this.list(wrapper);
        log.info("拉取盲盒历史记录,用户id:{},数量:{}", userId, messages.size());
        return messages;
    }

    private static Long getUserId(List<User> listUsers) {
        List<Long> onlineUserIds = new ArrayList<>();
        //离线用户
        List<Long> offlineUserIds = new ArrayList<>();
        Long userId = 0L;
        if (!listUsers.isEmpty()) {
            for (User user : listUsers) {
                if (Objects.equals(user.getOnlineStatus(), IMUserOnlineStatus.ON_LINE.code())) {
                    onlineUserIds.add(user.getId());
                } else {
                    offlineUserIds.add(user.getId());
                }
            }
            if (!onlineUserIds.isEmpty()) {
                //随机选择一个离线用户
                Random random = new Random();
                int index = random.nextInt(onlineUserIds.size());
                userId = onlineUserIds.get(index);
            } else {
                //随机选择一个在线用户
                Random random = new Random();
                int index = random.nextInt(offlineUserIds.size());
                userId = offlineUserIds.get(index);
            }
        }
        return userId;
    }
}
